package com.leyou.auth.service;

import com.leyou.auth.client.UserClient;
import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.util.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.user.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

@EnableConfigurationProperties(JwtProperties.class)
@Slf4j
@Service
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties props;

    public String login(String username, String password) {
        User user = null;
        try {
            // 校验用户名和密码
            user = userClient.queryUserBy(username, password);

            if (user == null) {
                throw new NullPointerException("user 不得为 null");
            }

        } catch (Exception e) {
            log.error("[授权中心] 远程调用异常", e);
            throw new LyException(ExceptionEnum.INVALID_USERNAME_OR_PASSWORD);
        }


        // 生成 token
        try {
            return JwtUtils.generateToken(new UserInfo(user.getId(), username),
                    props.getPrivateKey(), props.getExpire());
        } catch (Exception e) {
            log.error("[授权中心] 生成 token 失败，用户名称：{}", username, e);
            throw new LyException(ExceptionEnum.CREATE_TOKEN_ERROR);
        }
    }
}
